<?php

namespace library\request;

/**
 *Klasa przetwarzająca wyniki żądań HTTP
 *
 * @author Damian Jóźwiak
 */
class Response extends \library\Base{
    protected $response;
    /**
     * @read
     */
    protected $body=null;
    /**
     * @read
     */
    protected $headers=array();
    public function __construct($options = array()) {
        if (!empty($options["response"])){
            $response = $this->response = $options["response"];
        }
        parent::__construct($options);
        
        $pattern = "#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims";
        $matches=array();
        preg_match_all($pattern, $response, $matches);
        $_headers = array_pop($matches[0]);
        $headers = explode("\r\n", str_replace("\r\n\r\n", "", $_headers));
        $this->body=  str_replace($headers, "", $response);
        $version = array_shift($headers);
        preg_match("#HTTP/(\d\.\d)\s(\d\d\d)\s(.*)#", $version,$matches);
        $this->headers["Http-Version"] = $matches[1];
        $this->headers["Status-Code"] = $matches[2];
        $this->headers["Status"] = $matches[2]." ".$matches[3];
        foreach ($headers as $header){
            preg_match("#(.*?)\:\s(.*)#", $header,$matches);
            $this->headers[$matches[1]]=$matches[2];
        }
    }
    public function __toString() {
        return $this->getBody();
    }
}
